const app = getApp();
const req = require("../../utils/http.js");
const timeUtil = require('../../utils/util.js');

// 倒计时
function countdown(that) {
  //活动开始时间
  var itemBeginTime = that.data.beginTime
  //活动结束时间
  var itemTime = that.data.endTime
  // 获取活动开始时间毫秒数
  var BeginTime = Date.parse(itemBeginTime.replace(/-/g, '/'))
  // 获取活动结束时间毫秒数
  var EndTime = Date.parse(itemTime.replace(/-/g, '/'))
  //获取当前时间毫秒数
  var NowTime = timeUtil.formatTime(new Date());
  var NowStamp = Date.parse(NowTime)
  //活动开始时间-当前时间  正：还未开始，负：已经开始
  var total_micro_begin_second = BeginTime - NowStamp || []; //单位毫秒
  //活动结束时间-当前时间  正：还未结束  负：；已经结束
  var total_micro_second = EndTime - NowStamp || []; //单位毫秒

  // 渲染倒计时时钟
  let temp = null;
  if (total_micro_begin_second > 0 && total_micro_second > 0) { //还未开始  && 还未结束 
    temp = total_micro_begin_second
  } else { //活动开始
    temp = total_micro_second
  }
  that.setData({
    clock: dateformat(temp), //若已结束，此处输出'0天0小时0分钟0秒'
    NowStamp: NowStamp //当前时间毫秒数
  });

  let endSecond = null;
  // 活动执行完成，显示已截止 
  if (EndTime && total_micro_second <= 0) {
    if (endSecond != null) {
      clearTimeout(endSecond);
    }
    that.setData({
      clockHidd: true
    });
    return;
  }

  let beginSecond = null;
  // 开始执行限时抢购
  if (total_micro_begin_second <= 0) {
    that.setData({
      clockHidd: false,
      determine: true
    });

  }

  // 未开始限时抢购
  setTimeout(function () {
    if (total_micro_begin_second > 0) {
      total_micro_begin_second -= 1000;
    } else {
      total_micro_second -= 1000;
    }
    countdown(that);
  }, 1000)

}

// 时间格式化输出，如11天03小时25分钟19秒  每1s都会调用一次
function dateformat(micro_second) {
  // 总秒数
  var second = Math.floor(micro_second / 1000);
  // 天数
  var day = Math.floor(second / 3600 / 24);
  // 小时
  var hr = Math.floor(second / 3600 % 24);
  // 分钟
  var min = Math.floor(second / 60 % 60);
  // 秒
  var sec = Math.floor(second % 60);
  return day + "天" + hr + "小时" + min + "分钟" + sec + "秒";
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    background: [],
    prompt:'',
    categoryList: [{
      id: '1',
      name: '商品'
    }, {
      id: '2',
      name: '优惠卷'
    }],
    subjectType: '1',
    searchSongList: [], //放置返回数据的数组
    category:[],  //小程序类别
    page: 1,
    size: 10,
    total: '',
    // tab切换  
    currentTab:0,
    imgIcons:[],
    companyId:'',
    time:'',//当前时间
    isSwitchTab:false,
    homeAt:'/imgs/index/homeAt.png',
    my:'/imgs/index/my.png',
    tabBarList:[],
    GroupBuyLst:[]
  },

  // 轮播图
  getImgUrls() {
    let t = this
    let params = {}
    req.wxReq('/coupon/wxUser/getUploadFile', "GET", params).then(res => {
      if (res.data.code == 200) {
        t.setData({
          background: res.data.result
        })
      }
    })
  },
  // 图形列表
  configClik(companyId){
    let t = this
    req.wxReq(`/coupon/config/selectConfigByCompanyId/${companyId}`,"GET").then(res=>{
       t.setData({
         imgIcons:res.data.result
       })
    })
  },

  //限时抢购
  getSaleList: function () {
    req.wxReq('/coupon/wxActivityProduct/selectActivityProduct',"POST").then(res => {
      if (res.data.code == 200) {
        let t = this;
        let time = t.data.time; //当前时间
        let beginDate = res.data.result.beginTime;//开始时间
        let endDate = res.data.result.endTime;//结束时间
       
        time = time.replace("/", "-").replace("/", "-");
        if (res.data.result.activityProducts.length > 0) {
          if (time <= beginDate) {
            t.setData({
              endTime: endDate,
              beginTime: beginDate,
              determine: false // 显示距开始时间
            })
            countdown(t)
          } else {
            t.setData({
              endTime: endDate,
              beginTime: beginDate,
              determine: true
            })
            countdown(t)
          }
          countdown(t)
          t.setData({
            saleList: res.data.result.activityProducts,
            saleWrap:false,
          });
  
        }
        else {
          that.setData({
            saleWrap: true //限时抢购不显示
          });
        }

      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000
        });
      }
    })
  },

  //图形列表 ---跳转到相应的页面
  GraphicsClike(e){ 
    let t = this
    let url = e.currentTarget.dataset.transurl
    req.wxReq('/coupon/wxUser/isAuth', 'GET').then(res => {
      if (res.data.code == 200) {
        wx.navigateTo({
          url: url
        })
      }
      else { //未授权
        wx.showToast({
          title: '请先进行授权！',
          icon: 'none'
        })
        setTimeout(()=>{
          wx.navigateTo({
            url: '../publicToken/index',
          })
        },500)
     
      }
    })
 
  },
  //列表内容切换导航
  bindSubject: function (e) { //分类选择事件
    let t = this
    let page=1
    let {size} = t.data
    t.setData({
      isSwitchTab: true
    })
    
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      t.setData({
        currentTab: e.target.dataset.current,
        page,
        searchSongList:[],
        
        // params: { ...params, source }
      })
    
      t.setData({
        isSwitchTab: false
      })
    }
    //拉取列表信息
    this.contentsList(page,size,e.target.dataset.current)
  },


  //小程序类别
  selectListCategory: function () {
    req.wxReq('/coupon/wxUser/selectListCategory', "GET").then(res => {
      let t = this
      let currentTab ='0'
      if (res.data.code == 200) {
        t.setData({
          category: res.data.result
        })  
      }
      
      let {size}=t.data 
      let page = 1
      t.setData({
        page,
      })
    

    })
  },

  // 列表内容
  contentsList(page,size,currentTab) {
    let t = this
    let {
      current
    } = this.data
    let params = {};
    let url = ''
    if (currentTab == 0 ) {  //代金卷
      url = `/coupon/wxProduct/getCouponList/${page}/${size}`
    } else if (currentTab == 1){ //商品卷
      url = `/coupon/wxProduct/getBusinessCouponList/${page}/${size}`
    }
     else  { //商品
      url = `/coupon/wxProduct/getProductList/${page}/${size}`
      params = {categoryId: currentTab}
    }
    req.wxReq(url, "POST", params).then(res => {
      if(res.data.code==200){
        let entTimeTo = []
          let list = res.data.result.records
        let searchSongList = t.data.searchSongList.concat(list)
        // ---后台时间转换时间搓----
        if (list[0].endTime){
          for (var i = 0; i < list.length; i++) {
            entTimeTo[i] = Date.parse((list[i].endTime).replace(/-/g, '/'))
          }
        }
        t.setData({
          searchSongList,
          total: res.data.result.total,
          entTimeTo,
        })
     
  
      }else{
        wx.showToast({
          title: res.data.message,
          icon:'none',
          duration:600
        })
      }
     
    })
    // ---动态获取当前时间---
    setInterval(() => {
      var itemTime = timeUtil.formatTime(new Date());
      var itemStamp = Date.parse(itemTime)
      t.setData({
        itemStamp,
      })
    }, 1000)

  },
  
  //跳转商品详情
  goodsInfo(e) {
    console.log(e)
    let t = this
    let settype = e.currentTarget.dataset.settype   // 限时抢购 0：优惠价  1:商品
    let productId = e.currentTarget.dataset.id;
    let entTimeTo = e.currentTarget.dataset.enttimeto
    let group = e.currentTarget.dataset.group
    let currentTab = ''
    let ticketType = ''
    if (t.data.currentTab==1 || group=='group'){ //商品券
      ticketType= 0
    }else{
      ticketType = 1
      if (t.data.currentTab == 0) { //其他
        currentTab = 0
      } else {
        currentTab = 1
      }
    }
    if (entTimeTo == true) { //活动结束
      wx.showToast({
        title: '当前活动已结束',
        icon: 'none',
        duration: 2000
      })
      return
    } else {
      wx.navigateTo({
        url: '../product/index?productId=' + productId + '&currentTab=' + currentTab + '&settype=' + settype + '&ticketType=' + ticketType
      })
    }
  },
  // 查询当前用户
  isUserinfo() {
    let t = this
    let params = {}
    req.wxReq('/coupon/wxUser/isUserinfo', "GET", params).then(res => {
      if (res.data.code == 200) {
        let companyId = res.data.result.companyId
        t.configClik(companyId)
        wx.setStorageSync('openid', res.data.result.miniOpenid)
        wx.setStorageSync('isUifo', res.data.result)
      }else{
        wx.navigateTo({
          url:'你还未进行授权，请先授权！',
          icon:'none',
          duration:600
        })
      }
    })
  },
  //获取小程序信息
  getAppInfo() {
    let t = this
    let params = {}
    req.wxReq('/coupon/wxUser/getAppInfo', "GET", params).then(res => {
      if (res.data.code == 200) {
        wx.setStorageSync('appName', res.data.result.address)
        wx.setNavigationBarTitle({ //顶部名字
          title: res.data.result.address
        })
      }
    })
  },
 
  //爆品团购券
  GroupBuy(){
    let params ={}
    req.wxReq("/coupon/wxProduct/getHTypeBusinessCouponList","post",params).then(res=>{
      console.log('爆品团购',res)
      if(res.data.code==200){
        this.setData({
          GroupBuyLst:res.data.result
        })
      }else{
        wx.showToast({
          title: res.data.result,
          icon:'none',
          duration:900
        })
      }
   
    })
  },

  onLoad: function (options) {
  
    let t = this
    let url = app.globalData.baseUrl
    // 当前时间
    var time = timeUtil.formatTime(new Date());
    this.setData({
      time: time,
      paeg: 1
    })
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          wx.request({
            url: url + '/coupon/wxUser/login',
            method: 'GET',
            data: { code: res.code },
            header: {
              'content-type': 'application/json',
              'miniAppid': wx.getAccountInfoSync().miniProgram.appId
            },
            success: res => {
              if (res.data.code == 200) {
                let {page,size} = t.data
                wx.setStorageSync('token', res.data.result.token);
                // t.tabBar()
                t.getImgUrls() //轮播图
                t.isUserinfo() // 查询当前用户
                t.getAppInfo() //获取小程序信息
                t.getSaleList()  //限时抢购
                t.selectListCategory()
                t.GroupBuy()
              
              }

            },
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg);
        }
      }
    })
  
  },

  onShow: function () {
    let page =1
    this.setData({
      page: 1
    })
    this.setData({
      currentTab:0,
      searchSongList:[]
    })
  
    this.isUserinfo()
    this.contentsList(page, this.data.size, this.data.currentTab)

  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let t = this
    if (t.data.isSwitchTab==true){
      return
    }
    let page = t.data.page + 1;
    t.setData({
      page,
    }) 
    if (page > Math.ceil(this.data.total / this.data.size)) {
      wx.showToast({
        title: '到底了！！！',
        icon: 'none'
      })
      return;
    };
    t.contentsList(page, t.data.size, this.data.currentTab);
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { //刷新
    wx.showNavigationBarLoading()
    let t = this
    let page = 1
    let {
      size,
      params
    } = t.data
    t.setData({
      searchSongList: []
    })

    t.contentsList(page, size, this.data.currentTab);
    setTimeout(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    }, 1000);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  }
})